<template>
    <div class="race-box">
        <div class="race-item" v-for="(item, index) in raceData" :key="index">
            <el-divider v-if="index > 0"></el-divider>
            <el-form :model="item" :rules="rules" :ref="`raceData-${index}`" :inline="false" label-width="120px" class="act-rule-form">
                <el-form-item label="参选赛道" prop="raceType" required>
                    <el-select style="width:150px;" v-model="item.raceType">
                        <el-option label="高燃混剪" :value="1000"></el-option>
                        <el-option label="测评解说" :value="1001"></el-option>
                        <el-option label="游戏介绍" :value="1002"></el-option>
                        <el-option label="游戏单默认" :value="2000"></el-option>
                    </el-select>
                    <el-button type="primary" style="margin-left: 20px;" @click="addRace">添加赛道</el-button>
                    <el-button type="primary" style="margin-left: 20px;" @click="delRace(index)" v-if="index > 0">删除赛道</el-button>
                </el-form-item>
                <el-form-item label="赛道介绍" prop="raceDesc" required>
                    <div :id="`editor-${index}`" style="width: 500px"></div>
                </el-form-item>
                <el-form-item label="征集对象" prop="joinType" required>
                    <el-select style="width:150px;" v-model="item.joinType">
                        <el-option label="趣游星人" :value="0"></el-option>
                        <el-option label="创作者" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <div style="font-size: 16px; font-weight: 700;">
                    <el-form-item label="奖励配置"></el-form-item>
                </div>
                <el-form-item label="审核类型" prop="auditType" required>
                    <el-select style="width:150px;" v-model="item.auditType">
                        <el-option label="打榜" :value="0"></el-option>
                        <el-option label="人工审核" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="item.auditType < 1" label="打榜限制时间" prop="limitDay" required>
                    <el-input v-model="item.limitDay" style="width:120px"></el-input> 天
                </el-form-item>
                <el-form-item class="tag-form" v-if="item.auditType < 1 && targetType === 1" label="参与游戏" prop="gameInfoList" required>
                    <span class="span-btn" @click="addGame(index, null, 'outer')" style="margin-right: 10px;">添加游戏</span>
                    <el-tag class="game-tag" v-for="tag in item.gameInfoList" :key="tag.gameid" closable @close="closeOuterTag(tag.gameid, index)">
                        {{ tag.appName }}
                    </el-tag>
                </el-form-item>
                <div style="font-size: 14px; font-weight: 500;">
                    <el-form-item label="初审奖励"></el-form-item>
                </div>
                <div v-for="(it, ind) in item.collectionActivityFirstRewardVoList" :key="'firstReward-' + ind">
                    <el-form :model="it" :rules="rules" :ref="`firstReward-${ind}`" :inline="false" label-width="120px" class="act-rule-form">
                        <el-form-item label="奖励类型" prop="rewardType" required>
                            <el-select style="width:150px;" v-model="it.rewardType">
                                <el-option label="金币" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="奖励数量" prop="rewardValue" required>
                            <el-input v-model="it.rewardValue" style="width:150px"></el-input>
                        </el-form-item>
                        <el-button type="primary" style="margin-left: 20px;" @click="addFirstReward(index, ind)">添加</el-button>
                        <el-button type="primary" style="margin-left: 20px;" @click="delFirstReward(index, ind)" v-if="ind > 0">删除</el-button>
                    </el-form>
                </div>
                <div style="font-size: 14px; font-weight: 500;">
                    <el-form-item label="最终奖励">
                        <span class="span-btn" v-if="targetType === 1" @click="addLastReward(index)">添加目标</span>
                    </el-form-item>
                </div>
                <div style="margin-left: 40px;">
                    <el-table :data="item.collectionActivityLastRewardVoList" ref="table" style="width: 100%;">
                        <el-table-column width="130" label="达标类型">
                            <template slot-scope="scope">
                                <el-select v-if="item.auditType < 1"  style="width:120px;" v-model="scope.row.targetType">
                                    <el-option label="获赞数" :value="1"></el-option>
                                </el-select>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="130" label="达标准则">
                            <template slot-scope="scope">
                                <el-input v-if="item.auditType < 1" v-model="scope.row.targetValue" type="number" style="width:120px"></el-input>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="130" label="对应游戏">
                            <template slot-scope="scope">
                                <div v-if="item.auditType > 0 && targetType === 1" >
                                    <span class="span-btn" @click="addGame(index, scope.$index, 'inner')">添加游戏</span>
                                    <el-tag class="game-tag last-game-tag" v-for="tag in scope.row.gameInfoList" :key="tag.gameid" closable @close="closeInnerTag(tag.gameid, index, scope.$index)">
                                        {{ tag.appName }}
                                    </el-tag>
                                </div>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="130" label="奖励类型">
                            <template slot-scope="scope">
                                <div v-for="(rewardItem, i) in scope.row.collectionActivityRewardTypeLists" :key="i">
                                    <el-select :style="{'width': '120px', 'margin-top': i > 0 ? '10px' : '0'}" v-model="rewardItem.rewardType">
                                        <el-option label="金币" :value="1"></el-option>
                                    </el-select>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column min-width="150" label="奖励数量">
                            <template slot-scope="scope">
                                <div v-for="(rewardItem, i) in scope.row.collectionActivityRewardTypeLists" :key="i">
                                    <el-input v-model="rewardItem.rewardValue" type="number"  :style="{'width': '90px', 'margin-right': '5px', 'margin-top': i > 0 ? '10px' : '0'}"></el-input>
                                    <span class="span-btn" v-if="i > 0" @click="delReward(index, scope.$index, i)">删除</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button class="last-reward-btn" @click="addReward(index, scope.$index)" type="text" size="small">添加奖励</el-button>
                                <el-button class="last-reward-btn" @click="delLastReward(index, scope.$index)" style="margin-left: 0;" type="text" size="small" v-if="scope.$index > 0 && targetType === 1">删除目标</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- <div v-for="(it, ind) in item.collectionActivityLastRewardVoList" :key="ind + 1">
                    <el-form :model="it" :rules="rules" :ref="`lastReward-${ind}`" :inline="false" label-width="120px" class="act-rule-form">
                        <el-form-item v-if="item.auditType < 1" label="达标类型" prop="targetType" required>
                            <el-select style="width:150px;" v-model="it.targetType">
                                <el-option label="获赞数" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="item.auditType < 1" label="达标准则" prop="targetValue" required>
                            <el-input v-model="it.targetValue" type="number" style="width:150px"></el-input>
                        </el-form-item>
                        <el-form-item class="tag-form" v-if="item.auditType > 0 && targetType === 1" label="对应游戏" prop="gameInfoList" required>
                            <span class="span-btn" @click="addGame(index, ind, 'inner')">添加游戏</span>
                            <el-tag class="game-tag" v-for="tag in it.gameInfoList" :key="tag.gameid" closable @close="closeInnerTag(tag.gameid, index, ind)">
                                {{ tag.appName }}
                            </el-tag>
                        </el-form-item>
                        <div v-for="(rewardItem, i) in it.collectionActivityRewardTypeLists" :key="i">
                            <el-form :model="rewardItem" :rules="rules" :ref="`reward-${i}`" :inline="false" label-width="120px" class="act-rule-form">
                                <el-form-item label="奖励类型" prop="rewardType" required>
                                    <el-select style="width:150px;" v-model="rewardItem.rewardType">
                                        <el-option label="金币" :value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="奖励数量" prop="rewardValue" required>
                                    <el-input v-model="rewardItem.rewardValue" type="number" style="width:150px"></el-input>
                                </el-form-item>
                                <el-form-item label="">
                                    <span class="span-btn" v-if="i > 0" @click="delReward(index, ind, i)">删除奖励</span>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-form-item label=" ">
                            <span class="span-btn" v-if="ind > 0 && targetType === 1" @click="delLastReward(index, ind)">删除目标</span>
                            <span class="span-btn" @click="addReward(index, ind)">添加奖励</span>
                            <span class="span-btn" v-if="targetType === 1" @click="addLastReward(index)">添加目标</span>
                        </el-form-item>
                    </el-form>
                </div> -->
            </el-form>
        </div>
        <el-dialog class="addGame-dialog" title="添加游戏" :visible.sync="dialogVisible" width="900px">
            <addGame :dialogVisible="dialogVisible" :chooseGame="chooseGame" :isShow="dialogVisible" :dialogClose="dialogClose" />
        </el-dialog>
    </div>
</template>

<script>
import E from 'wangeditor'
import addGame from './addGame'

export default {
    components: {
        addGame
    },
    props: {
        collectionActivityVo: {},
        raceChange: {
            type: Function,
            default: null
        }
    },
    data () {
        return {
            raceData: this.collectionActivityVo,
            targetType: '',
            gameList: [],
            gameInfoList: [],
            gameLoading: false,
            dialogVisible: false,
            rules: {
                raceType: [
                    { required: true, message: '请选择参选赛道', trigger: 'change' }
                ],
                raceDesc: [
                    { required: true, message: '请填写赛道介绍', trigger: ['blur', 'change'] }
                ],
                joinType: [
                    { required: true, message: '请选择征集对象', trigger: ['blur', 'change'] }
                ],
                auditType: [
                    { required: true, message: '请选择审核类型', trigger: ['blur', 'change'] }
                ],
                limitDay: [
                    { required: true, message: '请选择打榜限制时间', trigger: ['blur', 'change'] }
                ],
                gameArr: [
                    { required: true, message: '请选择参与游戏', trigger: ['blur', 'change'] }
                ],
                rewardType: [
                    { required: true, message: '请选择奖励类型', trigger: 'change' }
                ],
                rewardValue: [
                    { required: true, message: '请填写奖励数量', trigger: ['blur', 'change'] }
                ],
                targetType: [
                    { required: true, message: '请选择达标类型', trigger: 'change' }
                ],
                targetValue: [
                    { required: true, message: '请填写达标数量', trigger: ['blur', 'change'] }
                ],
                gameInfoList: [
                    { required: true, message: '请添加游戏', trigger: 'change' }
                ]
            }
        }
    },
    created () {
        this.targetType = parseInt(this.$route.query.targetType)
        this.activityId = this.$route.query.id || null
        if (this.activityId) {
            this.raceData.map((item, index) => {
                if (item.collectionActivityLastRewardVoList.length < 1) {
                    item.collectionActivityLastRewardVoList = [
                        {
                            targetType: 1,
                            targetValue: '',
                            gameInfoList: [],
                            collectionActivityRewardTypeLists: [
                                {
                                    rewardType: 1,
                                    rewardValue: ''
                                }
                            ]
                        }
                    ]
                }
                item.gameArr = []
                item.gameInfoList.map(game => {
                    item.gameArr.push(game.gameid)
                })
                this.gameList.push(item.gameInfoList)
            })
        }
    },
    mounted () {
        if (this.targetType < 1) this.raceData[0].raceType = 2000
        if (this.activityId) {
            this.raceData.map((item, index) => {
                this.createEditor(index)
            })
        } else {
            this.createEditor(0)
        }
    },
    watch: {
        'raceData': {
            handler: function (data) {
                this.raceChange(data)
            },
            immediate: true
        }
    },
    methods: {
        validateForm () {
            let flag = true
            let isLastReward = false
            for (let i in this.raceData) {
                this.$refs[`raceData-${i}`][0].validate(valid => {
                    if (!valid) {
                        flag = false
                    }
                })
                for (let firstI in this.raceData[i].collectionActivityFirstRewardVoList) {
                    this.$refs[`firstReward-${firstI}`][0].validate(valid => {
                        if (!valid) {
                            flag = false
                        }
                    })
                }
                for (let lastI in this.raceData[i].collectionActivityLastRewardVoList) {
                    if (this.raceData[i].auditType < 1 && !this.raceData[i].collectionActivityLastRewardVoList[lastI].targetValue) {
                        flag = false
                        isLastReward = true
                    }
                    for (let rewardI in this.raceData[i].collectionActivityLastRewardVoList[lastI].collectionActivityRewardTypeLists) {
                        if (!rewardI.rewardValue) {
                            flag = false
                            isLastReward = true
                        }
                    }
                }
                // for (let lastI in this.raceData[i].collectionActivityLastRewardVoList) {
                //     this.$refs[`lastReward-${lastI}`][0].validate(valid => {
                //         if (!valid) {
                //             flag = false
                //         }
                //     })
                //     for (let rewardI in this.raceData[i].collectionActivityLastRewardVoList[lastI].collectionActivityRewardTypeLists) {
                //         this.$refs[`reward-${rewardI}`][0].validate(valid => {
                //             if (!valid) {
                //                 flag = false
                //             }
                //         })
                //     }
                // }
            }
            this.raceChange(this.raceData, isLastReward)
            return flag
        },
        addRace () {
            let raceType = 1000
            if (this.targetType < 1) raceType = 2000
            let item = {
                raceType,
                raceDesc: '',
                joinType: null,
                auditType: null,
                limitDay: null,
                gameInfoList: [],
                collectionActivityFirstRewardVoList: [
                    {
                        rewardType: '',
                        rewardValue: ''
                    }
                ],
                collectionActivityLastRewardVoList: [
                    {
                        targetType: 1,
                        targetValue: '',
                        gameInfoList: [],
                        collectionActivityRewardTypeLists: [
                            {
                                rewardType: 1,
                                rewardValue: ''
                            }
                        ]
                    }
                ]
            }
            this.raceData.push(item)
            let index = this.raceData.length - 1
            this.$nextTick(() => {
                this.createEditor(index)
            })
        },
        addGame (index, ind, type) {
            this.chooseGameObj = { index, ind, type }
            this.dialogVisible = true
        },
        chooseGame (gameList) {
            if (gameList.length < 1) return
            let game = null
            if (this.chooseGameObj.type === 'outer') {
                game = [].concat(this.raceData[this.chooseGameObj.index].gameInfoList || [])
            } else {
                game = [].concat(this.raceData[this.chooseGameObj.index].collectionActivityLastRewardVoList[this.chooseGameObj.ind].gameInfoList || [])
            }
            let flag = true
            let arr = []
            for (let i = 0; i < gameList.length; i++) {
                flag = true
                for (let j = 0; j < game.length; j++) {
                    if (game[j].gameid === gameList[i].gameid) {
                        flag = false
                    }
                }
                if (flag) arr.push(gameList[i])
            }
            if (this.chooseGameObj.type === 'outer') {
                this.raceData[this.chooseGameObj.index].gameInfoList = [...game, ...arr]
            } else {
                this.raceData[this.chooseGameObj.index].collectionActivityLastRewardVoList[this.chooseGameObj.ind].gameInfoList = [...game, ...arr]
            }
            this.dialogVisible = false
        },
        dialogClose () {
            this.dialogVisible = false
        },
        closeInnerTag (tagId, index, ind) {
            let game = this.raceData[index].collectionActivityLastRewardVoList[ind].gameInfoList
            game.map((item, i) => {
                if (item.gameid === tagId) {
                    game.splice(i, 1)
                    this.raceData = [].concat(this.raceData)
                }
            })
        },
        closeOuterTag (tagId, index) {
            let game = this.raceData[index].gameInfoList
            game.map((item, i) => {
                if (item.gameid === tagId) {
                    game.splice(i, 1)
                    this.raceData = [].concat(this.raceData)
                }
            })
        },
        gameChange (value, index) { // 修改参与游戏
            console.log(value, this.gameList)
            this.gameList[index].map(item => {
                if (item.gameid === value[value.length - 1]) {
                    this.raceData[index].gameInfoList.push({
                        gameid: item.gameid,
                        appName: item.appName
                    })
                }
            })
        },
        delRace (index) {
            this.raceData.splice(index, 1)
        },
        delReward (index, ind, i) {
            this.raceData[index].collectionActivityLastRewardVoList[ind].collectionActivityRewardTypeLists.splice(i, 1)
        },
        delLastReward (index, ind) {
            this.raceData[index].collectionActivityLastRewardVoList.splice(ind, 1)
        },
        addReward (index, i) {
            console.log(index, i)
            this.raceData[index].collectionActivityLastRewardVoList[i].collectionActivityRewardTypeLists.push({
                rewardType: '',
                rewardValue: ''
            })
        },
        addLastReward (index) {
            this.raceData[index].collectionActivityLastRewardVoList.push({
                targetType: 1,
                targetValue: '',
                gameInfoList: [],
                collectionActivityRewardTypeLists: [
                    {
                        rewardType: 1,
                        rewardValue: ''
                    }
                ]
            })
        },
        addFirstReward (index, ind) {
            this.raceData[index].collectionActivityFirstRewardVoList.push({
                rewardType: '',
                rewardValue: ''
            })
        },
        delFirstReward (index, ind) {
            this.raceData[index].collectionActivityFirstRewardVoList.splice(ind, 1)
        },
        filterMethod (res, index) {
            clearTimeout(this.timerId)
            if (!res) {
                this.gameLoading = false
                return
            }
            this.gameLoading = true
            this.timerId = setTimeout(() => {
                this.getgameList(res, index)
            }, 1000)
        },
        async getgameList (keyword, index) {
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 100
            }
            let res = await this.$http.post('/home/findGames', params)
            if (res.code === '0') {
                this.gameList[index] = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },
        // 初始化富文本编辑器
        createEditor (index) {
            this.editor = new E(`#editor-${index}`)
            this.editor.customConfig.uploadImgServer = '/admin/file/uploadPic'
            this.editor.customConfig.uploadImgParams = {
                needTransform: 1
            }
            this.editor.customConfig.uploadFileName = 'file'
            this.editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                // 图片上传之前触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
                // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                // return {
                //     prevent: true,
                //     msg: '放弃上传'
                // }
                },
                success: function (xhr, editor, result) {
                // 图片上传并返回结果，图片插入成功之后触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                // 图片上传并返回结果，但图片插入错误时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                error: function (xhr, editor) {
                // 图片上传出错时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },
                timeout: function (xhr, editor) {
                // 图片上传超时时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data
                    insertImg(url)

                // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }
            this.editor.customConfig.zIndex = 100
            this.editor.customConfig.menus = [
                // 'head', // 标题
                'bold', // 粗体
                // 'fontSize', // 字号
                // 'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                // 'list', // 列表
                'justify', // 对齐方式
                // 'quote', // 引用
                // 'emoticon', // 表情
                'image', // 插入图片
                // 'table', // 表格
                // 'video', // 插入视频
                // 'code', // 插入代码
                'undo', // 撤销
                'redo' // 重复
            ]
            this.editor.customConfig.onchange = (html) => {
                this.raceData[index].raceDesc = html
            }
            this.editor.create()
            this.editor.txt.html(this.raceData[index].raceDesc)
        }
    }
}
</script>

<style lang="scss" scoped>
    .race-box {
        max-width: 800px;
        .act-rule-form {
            /deep/.el-form-item__content {
                margin-left: 0 !important;
            }
        }
        .span-btn {
            color: cadetblue;
            cursor: pointer;
        }
        .addGame-dialog {
            /deep/.el-dialog__body {
                padding-top: 0;
            }
        }
        .game-tag {
            margin-right: 10px;
        }
        .last-game-tag {
            margin-bottom: 5px;
        }
        .tag-form {
            display: flex !important;
            /deep/.el-form-item__content {
                flex: 1;
            }
        }
        .last-reword-box {
            border: 1px solid red;
            .last-reword-header {
                display: flex;
                .last-reword-item {
                    flex: 1;
                    text-align: center;
                }
            }
        }
        .last-reward-btn {
            padding:5px;
        }
    }
</style>
